import 'dart:convert';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/media_library/media_library_index/even/media_library_index_refresh_even.dart';
import 'package:e_reception_flutter/net/net_api.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/building_index/building_index_terminal_list_response_bean.dart';
import 'package:e_reception_flutter/ui/building_index/change_to_diy_or_module_page_event.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_building_index_terminal_settings_event.dart';
import 'package:e_reception_flutter/ui/building_index/refresh_diy_page_event.dart';
import 'package:e_reception_flutter/ui/building_index/show_set_module_type_bubble_event.dart';
import 'package:e_reception_flutter/ui/common/update_diy_center_info_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/bg_music/refresh_terminal_bg_music_list_event.dart';
import 'package:e_reception_flutter/utils/file_utils.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import '../../app_main.dart';
import 'bean/bg_terminal_music_list_response_bean.dart';


class BgTerminalMusicListViewModel extends BaseViewModel {

  ValueNotifier<PlaceHolderStatusType> statusTypeValueNotifier;
  ValueNotifier<List<MusicListBean>> musicListValueNotifier;
  ValueNotifier<String> musicFlagValueNotifier;
  ValueNotifier<MusicListDataBean> musicListAndFlagValueNotifier;

  BgTerminalMusicListViewModel(BaseState<StatefulWidget> state)
      : super(state){
    statusTypeValueNotifier = ValueNotifier(PlaceHolderStatusType.loading);
    musicListValueNotifier = ValueNotifier(null);
    musicFlagValueNotifier = ValueNotifier(null);
    musicListAndFlagValueNotifier = ValueNotifier(null);
  }

  ///获取音乐列表
  void getBgMusicList(String hsn){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    String cacheKey = NetApi.GET_BG_MUSIC_LIST + (UserRepository.getInstance().getCacheKeySuffix()?? "")
        + hsn;
    ///获取缓存数据
    Future<String> future = SharePreferenceUtil.getString(cacheKey);
    future.then((jsonStr){
      if(!StringUtils.isEmpty(jsonStr)){
        print("获取缓存音乐列表：" + cacheKey + "   " + jsonStr);
        Map map = json.decode(jsonStr);
        BgTerminalMusicListResponseBean bean = BgTerminalMusicListResponseBean.fromMap(map);
        if(bean != null){
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            musicListAndFlagValueNotifier?.value = bean?.data;
            musicListValueNotifier?.value = bean?.data?.musicList;
            musicFlagValueNotifier?.value = bean?.data?.musicflg;
            if(bean?.data?.musicList?.isEmpty??false){
              statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
            }
          }
          loading(false);
        }
        getBgMusicListOnLine(hsn, cacheKey, bean);
      }else{
        getBgMusicListOnLine(hsn, cacheKey, null);
      }
    });
  }

  void getBgMusicListOnLine(String hsn, String cacheKey, BgTerminalMusicListResponseBean bean){
    VgHttpUtils.get(NetApi.GET_BG_MUSIC_LIST,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          BgTerminalMusicListResponseBean bean =
          BgTerminalMusicListResponseBean.fromMap(val);
          if(!isStateDisposed){
            statusTypeValueNotifier?.value = null;
            if(bean != null && bean.data != null){
              musicListAndFlagValueNotifier?.value = bean?.data;
              musicListValueNotifier?.value = bean?.data?.musicList;
              musicFlagValueNotifier?.value = bean?.data?.musicflg;
              if(bean?.data?.musicList?.isEmpty??false){
                statusTypeValueNotifier?.value = PlaceHolderStatusType.empty;
              }
            }
          }
          loading(false);
          if(bean!=null){
            SharePreferenceUtil.putString(cacheKey, json.encode(bean));
            print("缓存音乐列表详情：" + cacheKey + "   " + json.encode(bean));
          }
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
          if(bean == null){
            statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
          }
        }
    ));
  }

  ///背景音乐开关
  ///00开启 01关闭
  void openOrCloseBgMusic(BuildContext context, String hsn, String musicflg, {VoidCallback callback}){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    loading(true,);
    VgHttpUtils.get(NetApi.OPEN_OR_CLOSE_MUSIC,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "musicflg": musicflg ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          if(callback != null && "00" == musicflg){
            callback.call();
          }
          VgEventBus.global.send(new RefreshTerminalBgMusicListEvent());
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///从终端移除某个bg
  void deleteBgByHsn(BuildContext context, String hsn, String id){
    if(StringUtils.isEmpty(hsn)){
      return;
    }
    loading(true,);
    VgHttpUtils.get(NetApi.DELETE_BG_MUSIC,params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "hsn": hsn ?? "",
      "id": id ?? "",
    },callback: BaseCallback(
        onSuccess: (val){
          loading(false);
          VgEventBus.global.send(new RefreshTerminalBgMusicListEvent());
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);
        }
    ));
  }

  ///分类排序
  void modifyOrder(BuildContext context, String ids, String hsn){
    VgHudUtils.show(context, "请稍后");
    VgHttpUtils.get(NetApi.MODIFY_BG_MUSIC_ORDER, params: {
      "authId":UserRepository.getInstance().authId ?? "",
      "ids":ids??"",
      "hsn":hsn??"",
    },callback: BaseCallback(
        onSuccess: (val){
          VgEventBus.global.send(new RefreshTerminalBgMusicListEvent());
          VgHudUtils.hide(context);
        },
        onError: (msg){
          loading(false);
          VgToastUtils.toast(AppMain.context, msg);}
    ));
  }

  @override
  void onDisposed() {
    statusTypeValueNotifier?.dispose();
    musicListValueNotifier?.dispose();
    super.onDisposed();
  }
}
